
import React, { useState } from 'react';
import { useDispatch } from 'react-redux';
import { setUsername } from '../lib/store/usernameSlice';
import { FaBackspace } from "react-icons/fa";
import { MdOutlineEmail } from "react-icons/md";
import { VscShield } from "react-icons/vsc";
import { FaRegUserCircle } from "react-icons/fa";
import { RiLockPasswordLine } from "react-icons/ri";
import { RiLockPasswordFill } from "react-icons/ri";
import postData from '@/lib/postData';
import url from '@/lib/url';


type props = {
    setIsLogin: React.Dispatch<React.SetStateAction<boolean>>;
    setIsReadyToLog: React.Dispatch<React.SetStateAction<boolean>>;
};

const Login: React.FC<props> = ({ setIsLogin, setIsReadyToLog, }) => {
    const [isLogup, setIsLogup] = useState(false);
    const [isForget, setIsForget] = useState(false);
    const [isSendingEmail, setIsSendingEmail] = useState(false);
    const [countTime, setCountTime] = useState(0);

    const dispatch = useDispatch();

    const [userObject, setUserObject] = useState({
        username: "",
        password: "",
        isLogin: false,
    });

    const [userLogupObject, setUserLogupObject] = useState({
        email: "",
        passCode: "",
        username: "",
        password: "",
        confirmPassword: ""
    });

    const handleLogupSubmit = (e: React.FormEvent) => {
        e.preventDefault();
        if (userLogupObject.email === "" || userLogupObject.passCode === "" || userLogupObject.username === "" || userLogupObject.password === "" || userLogupObject.confirmPassword === "") {
            alert("请填写完整信息");
            return;
        }
        if (userLogupObject.password !== userLogupObject.confirmPassword) {
            alert("两次密码不一致，请重试");
            return;
        }
        postData((url + "/api/logup/isAvailableEmailAndUsername"), { username: userLogupObject.username, email: userLogupObject.email }).then((res) => {
            if (!res.canLogup) {
                alert(res.type);
                return;
            }
        });

        postData(url + '/api/logup/judgePassCode', { email: userLogupObject.email, passcode: userLogupObject.passCode }).then((res) => {
            if (!res.passcode) {
                alert("验证码错误，请重试");
                return;
            } else {
                alert("注册成功，请登录");
                postData(url + '/api/logup/logup', { username: userLogupObject.username, email: userLogupObject.email, password: userLogupObject.password });
                setIsLogup(false);

            }
        });

    };

    const handleLoginSubmit = (e: React.FormEvent) => {
        e.preventDefault();
        postData(url + "/api/login/login", { username: userObject.username, password: userObject.password }).then((res) => {
            if (res.login) {
                dispatch(setUsername(userObject.username));
                setIsReadyToLog(false);
                setIsLogin(true);
            } else {
                alert(res.type);
            };
        });
    };

    const handleClose = () => {
        setIsReadyToLog(false);
    };

    const handleSendEmail = () => {
        postData(url + '/api/logup/sendemail', { email: userLogupObject.email }).then((res) => {
            if (!res.availableEmail) {
                console.log(res);
                alert(res.type);
                setCountTime(0);
                return;
            }
        });

        setCountTime(60);
        setIsSendingEmail(true);
        const time = setInterval(() => {
            setCountTime((prevCount) => {
                if (prevCount === 0) {
                    clearInterval(time); // 如果倒计时为0，清除定时器
                    setIsSendingEmail(false); // 更新发送状态为 false
                    return 0; // 返回倒计时为0
                }
                return prevCount - 1; // 否则倒计时减1
            });
        }, 1000);


    };

    const changepage = () => {
        if (isLogup) {
            // 注册界面
            return (
                <fieldset onClick={(e) => e.stopPropagation()} className={`z-100 absolute bg-base-200 p-4 border border-base-300 rounded-box w-xs fieldset animation-centerin`}>
                    <div className='flex flex-col px-2'>
                        <header className='flex justify-between items-center text-secondary text-2xl'>
                            <p>注册</p>
                            <FaBackspace className='hover:cursor-pointer' onClick={() => setIsLogup(false)} />
                        </header>
                        <form onSubmit={handleLogupSubmit}>
                            <label className="my-2 fieldset-label input">
                                <MdOutlineEmail className='text-xl' />
                                <input type="email" value={userLogupObject.email} onChange={(e) => setUserLogupObject({ ...userLogupObject, email: e.target.value })} className="text-black" placeholder="请输入邮箱" />
                                {isSendingEmail ? <p>{countTime}</p> : <p onClick={handleSendEmail} className='text-primary text-xs hover:cursor-pointer'>发送验证码</p>}
                            </label>

                            <label className="my-2 fieldset-label input">
                                <VscShield className='text-xl' />
                                <input type="text" value={userLogupObject.passCode} onChange={(e) => setUserLogupObject({ ...userLogupObject, passCode: e.target.value })} className="text-black" placeholder="请输入验证码" />
                            </label>
                            <label className="my-2 fieldset-label input">
                                <FaRegUserCircle className='text-lg' />
                                <input type="text" value={userLogupObject.username} onChange={(e) => setUserLogupObject({ ...userLogupObject, username: e.target.value })} className="text-black" placeholder="请输入用户名" />
                            </label>

                            <label className="my-2 fieldset-label input">
                                <RiLockPasswordLine className='text-lg' />
                                <input type="password" value={userLogupObject.password} onChange={(e) => setUserLogupObject({ ...userLogupObject, password: e.target.value })} className="text-black" placeholder="请输入密码" />
                            </label>

                            <label className="my-2 fieldset-label input">
                                <RiLockPasswordFill className='text-lg' />
                                <input type="password" value={userLogupObject.confirmPassword} onChange={(e) => setUserLogupObject({ ...userLogupObject, confirmPassword: e.target.value })} className="text-black" placeholder="请再输入密码" />
                            </label>

                            <button className="btn-block mt-2 btn btn-neutral" type='submit' onClick={handleLogupSubmit}>注册</button>
                        </form>

                    </div>
                </fieldset>
            );
        } else if (isForget) {
            // 忘记密码界面
            return (
                <fieldset onClick={(e) => e.stopPropagation()} className={`z-100 absolute bg-base-200 p-4 border border-base-300 rounded-box w-xs fieldset animation-centerin`}>
                    <div className='flex flex-col'>
                        <header className='flex justify-between items-center text-secondary text-2xl'>
                            <p>忘记密码</p>
                            <FaBackspace className='hover:cursor-pointer' onClick={() => setIsForget(false)} />
                        </header>

                    </div>
                </fieldset>
            );
        } else {
            // 登录界面
            return (
                <fieldset onClick={(e) => e.stopPropagation()} className={` bg-base-200 p-4 border border-base-300 rounded-box w-xs fieldset animation-centerin`}>
                    <div className="flex justify-between text-secondary text-2xl fieldset-legend">
                        <p className=''>登录</p>
                        <label htmlFor="my_modal_6" className='btn btn-circle btn-sm' onClick={handleClose}>x</label>
                    </div>
                    <form onSubmit={handleLoginSubmit}>
                        <label className="my-1 fieldset-label">用户名</label>
                        <input type="email" value={userObject.username} onChange={(e) => setUserObject({ ...userObject, username: e.target.value })} className="input" placeholder="请输入用户名" />

                        <label className="my-1 fieldset-label">密码</label>
                        <input type="password" value={userObject.password} onChange={(e) => setUserObject({ ...userObject, password: e.target.value })} className="input" placeholder="请输入密码" />
                        <div className='flex justify-between mt-1.5'>
                            <p className="text-primary hover:cursor-pointer" onClick={() => setIsForget(true)} >忘记密码</p>
                            <p className="text-primary hover:cursor-pointer" onClick={() => setIsLogup(true)}>注册账号</p>
                        </div>
                        <div className="text-center">
                            <p>目前实现功能，与ai问答，暂未支持模型联网，采用月之暗面V1-8K模型，感兴趣可以登陆尝试</p>
                            <ul>规划实现功能
                                <li>1.添加好友功能及线上聊天</li>
                                <li>2.添加AI联网问答</li>
                                <li>3.实现流式输出，并根据输出内容进行排版</li>
                            </ul>
                        </div>

                        <button className="btn-block mt-2 btn btn-neutral" type='submit' onClick={handleLoginSubmit}>登录</button>
                    </form>
                </fieldset>
            );
        }
    };

    return (
        <div onClick={() => setIsReadyToLog(false)} className="flex justify-center items-center bg-black/20 min-w-screen min-h-screen">
            {changepage()}
        </div>
    );
};


export default Login;
